import { FC, ReactElement, useState } from "react";
import styled, { css } from "styled-components";
import { ITag } from "../../api/tagApi";
import { ThemeText } from "../BUI/View/ThemeView";
import { fadeIn, OptionalItem } from "../commentStyled";

interface IProps {
  data: Array<ITag>;
  defaultValue?: string;
  onChange: (tag: string) => void;
}

const Options: FC<IProps> = ({
  data,
  defaultValue = "按标签筛选",
  onChange,
}): ReactElement => {
  const [selected, setSelected] = useState(defaultValue);
  const [open, setOpen] = useState(false);

  return (
    <Container>
      <OptionalItem
        onMouseEnter={() => setOpen(state => !state)}
        onTouchStart={() => setOpen(state => !state)}
      >
        {selected}
      </OptionalItem>
      {open ? (
        <UL onMouseLeave={() => setOpen(false)}>
          <li
            onClick={() => {
              setSelected("全部");
              setOpen(false);
              onChange("");
            }}
          >
            全部
          </li>
          {data.map(tag => (
            <li
              onClick={() => {
                setSelected(tag.name);
                setOpen(false);
                onChange(tag.name);
              }}
              key={tag._id}
            >
              {tag.name}
            </li>
          ))}
        </UL>
      ) : null}
    </Container>
  );
};

export default Options;

const Container = styled.div`
  position: relative;
  ${OptionalItem} {
    margin: 0;
    background: #666;
  }
`;

const UL = styled.ul`
  display: inline-block;
  max-height: 20rem;
  overflow-y: scroll;
  overflow-x: hidden;
  position: absolute;
  top: 0;
  left: 0;
  z-index: ${props => props.theme.index.max};
  background: ${props => props.theme.bg};
  ${ThemeText};
  border-radius: 5px;
  padding: 0.1rem;
  margin: 0;
  box-shadow: 0 0 10px 0
    ${props => (props.theme.mode == "dark" ? "#000" : "#aaa")};
  animation: ${fadeIn} 0.2s linear;

  @media (max-width: ${props => props.theme.media.phone}) {
    top: 2rem;
    right: 0;
    left: auto;
  }

  li {
    list-style: none;
    padding: 0.4rem;
    cursor: pointer;
    transition: background 0.3s linear;
    margin: 0.1rem 0;
    &:hover {
      background: ${props => props.theme.shadow};
    }
  }
`;
